import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shop/shop/life/Index.dart';
import 'package:shop/shop/merchant/GoodsTypePage.dart';
import 'package:shop/shop/merchant/GukeList.dart';
import 'package:shop/shop/merchant/JingyingFenxi.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/merchant/MerchantSetting.dart';
import 'package:shop/shop/merchant/Peisongfei.dart';
import 'package:shop/shop/merchant/jishipages/JiShiListPage.dart';

import 'ServiceEdit.dart';
// import 'package:shop/shop/merchant/ServiceEdit.dart';

class MyCenter extends StatefulWidget {
  MyCenter({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyCenter createState() => _MyCenter();
}

class _MyCenter extends State<MyCenter> {

  String merchantID="";         //商户ID
  String merchantName="点击登录";//商户名称
  String jifen="0";             //商户可用积分
  bool isLogin=false;           //是否登录
  var tupian;                   //商户图片
  double jinrizongshouyi=0.00;  //今日总收益
  int jinridanliagn=0;          //今日单量
  String merchantStatus;        //商户状态
  String mType = "0";           //商户类型（0：外卖型商户  1：服务型商户）
  String icon = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170215%2F0edb3abc2de44179af2020ce1f05894a_th.jpg&refer=http%3A%2F%2Fimg.mp.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632910571&t=404554f48d58eaa5e975b7ca828cb69b";//商户头像
  SharedPreferences prefs;

  // 构造方法
  _MyCenter() {
    _getUserInfo();
  }

  // 获取用户信息
  void _getUserInfo () async {
    // 获取内存存储的用户id
    prefs = await SharedPreferences.getInstance();
    if(prefs.getBool("isLogin")){
      merchantID = prefs.getString("merchantID");
      merchantName = prefs.getString("merchantName");
      mType = prefs.getString("mType");
      // merchantName="暂时写死了";
      // isLogin = prefs.getBool("isLogin");
      // isLogin=true;
      var x = await HttpUtil().get("/waimai/merchant/getByMerchantID?mId="+merchantID);//根据商户ID查询商户详情
      if(x['code']==200){
        jifen = x['data']['jifen'].toString();
        icon = x['data']['picture'];
        if(icon==null || icon==""){
          icon = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170215%2F0edb3abc2de44179af2020ce1f05894a_th.jpg&refer=http%3A%2F%2Fimg.mp.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632910571&t=404554f48d58eaa5e975b7ca828cb69b";
        }else{
          icon = Config.getInstance().getHost()+icon;
        }
        int yingyeStatus = x['data']['yingyeStatus'];
        if(yingyeStatus==0){
          merchantStatus = "休息中";
        }else{
          merchantStatus = "营业中";
        }
      }
      var y = await HttpUtil().get("/waimai/mOder/merchantTodayOrderInfo?mId="+merchantID+"&mType="+mType);//根据商户ID查询商户今日营业额和订单数
      if(y['code']==200){
        jinridanliagn = y['data']['danliang'];
        if(y['data'].length<2){
          jinrizongshouyi = 0.00;
        }else{
          jinrizongshouyi = y['data']['zonge'];
        }
      }
      setState(() {});
    }
    if(merchantName==null || merchantName==""){
      merchantName="点击登录";
      isLogin = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return ConstrainedBox(
      constraints: BoxConstraints.expand(),
      child: Container(
        padding: EdgeInsets.only(top: ScreenUtil().setHeight(30)),
        color: Colors.black12,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
              top: 0,
                child: Container(
                  child: Text('门店管理',style: TextStyle(fontSize: ScreenUtil().setHeight(20)),),
                )
            ),
            Positioned(
              right: 0,
                top: ScreenUtil().setHeight(-10),
                child:IconButton(icon: Icon(Icons.settings), onPressed: () async {
                  Map value = await MyRoute.push(MerchantSetting());
                  if(value!=null){
                    merchantName=value['merchantName'];
                    if(value['icon'].toString().startsWith("upload")){
                      icon=Config.getInstance().getHost()+value['icon'];
                    }else{
                      icon=Config.getInstance().getHost()+"upload/merchant/"+value['icon'];
                    }
                    setState(() {

                    });
                  }
                })
            ),
            Positioned(
              top: ScreenUtil().setHeight(50),
                child: Container(
                  width: ScreenUtil().setHeight(400),
              margin: EdgeInsets.symmetric(horizontal: ScreenUtil().setHeight(20)),
              padding: EdgeInsets.all(ScreenUtil().setHeight(10)),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(5)) ,
                color: Colors.white,
              ),
              child:
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        child: Row(
                          children: [
                            GestureDetector(child: Container(
                              height: ScreenUtil().setHeight(80),
                              width: ScreenUtil().setWidth(80),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius:BorderRadius.circular(15),
                                image: new DecorationImage(
                                  image: new NetworkImage(icon),
                                  //这里是从assets静态文件中获取的，也可以new NetworkImage(）从网络上获取
                                  // centerSlice: new Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0),
                                ),
                              ),
                            ),onTap: () async {
                              if(merchantID!=null && merchantID!=""){
                                var s = await ImagePicker.pickImage(source: ImageSource.gallery);
                                // _iconPath=s;
                                File file = new File(s.path);
                                var result = await HttpUtil().upload("/upload", file);
                                tupian = result['data'];
                                var res = await HttpUtil().get("waimai/merchant/updateMerchant?mid=${merchantID}&picture=${tupian}",);
                                if(res['code']==200){
                                  setState(() {
                                    icon = Config.getInstance().getHost()+"upload/merchant/"+tupian;
                                  });
                                }else{
                                  Fluttertoast.showToast(
                                      msg: res['msg'],
                                      toastLength: Toast.LENGTH_SHORT,
                                      gravity: ToastGravity.BOTTOM,
                                      timeInSecForIosWeb: 1,
                                      backgroundColor: Colors.black45,
                                      textColor: Colors.white,
                                      fontSize: 16.0
                                  );
                                }
                              }
                            },),
                            Container(
                                padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                                child: isLogin ? Text(merchantName,style: TextStyle(color: Colors.black,fontSize: 15,fontWeight: FontWeight.w600,letterSpacing: 1,fontStyle: FontStyle.normal),) : GestureDetector(child: Text(merchantName,style: TextStyle(color: Colors.black,fontSize: 15),),onTap: (){
                                },)
                            ),
                          ],
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
                        child: Row(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                    child: new DropdownButton(
                                      value: merchantStatus,
                                      dropdownColor: Colors.white,
                                      underline: SizedBox(height:10,),
                                      onChanged: (T) async {
                                        merchantStatus = T;
                                        int yingyeStatus=0;//营业状态
                                        if(merchantStatus=="营业中"){
                                          yingyeStatus=1;
                                        }
                                        //修改商户在线状态
                                        var x = await HttpUtil().get("/waimai/merchant/updateYingyeStatus?mid="+merchantID+"&yingyeStatus="+yingyeStatus.toString());
                                        if(x['code']==500){
                                          Fluttertoast.showToast(
                                              msg: x['msg'],
                                              toastLength: Toast.LENGTH_SHORT,
                                              gravity: ToastGravity.BOTTOM,
                                              timeInSecForIosWeb: 1,
                                              backgroundColor: Colors.black45,
                                              textColor: Colors.white,
                                              fontSize: 16.0
                                          );
                                        }else{
                                          Fluttertoast.showToast(
                                              msg: "修改成功",
                                              toastLength: Toast.LENGTH_SHORT,
                                              gravity: ToastGravity.BOTTOM,
                                              timeInSecForIosWeb: 1,
                                              backgroundColor: Colors.black45,
                                              textColor: Colors.white,
                                              fontSize: 16.0
                                          );
                                          setState(() {});
                                        }
                                      },
                                      items: getListData(),
                                      iconSize: 0,//设置三角标icon的大小
                                    )
                                )
                              ],
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
            )
            ),
            Positioned(
              top: ScreenUtil().setHeight(150),
                child: Container(
                  width: ScreenUtil().setHeight(400),
                  padding: EdgeInsets.symmetric(vertical: ScreenUtil().setHeight(20)),
                  // color: Colors.white,
                  child: mType=="0" ? Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Column(
                        children: [
                          Text(jinrizongshouyi.toString(),style: TextStyle(fontSize: 25,fontWeight: FontWeight.w600),),
                          Text("今日营业总额")
                        ],
                      ),
                      SizedBox(width: 1,height: ScreenUtil().setHeight(20),child: DecoratedBox(decoration: BoxDecoration(color: Colors.grey),),),
                      Column(
                        children: [
                          Text(jinridanliagn.toString(),style: TextStyle(fontSize: ScreenUtil().setHeight(25),fontWeight: FontWeight.w600),),
                          Text("今日外卖量/单")
                        ],
                      ),
                      // SizedBox(width: 1,height: 20,child: DecoratedBox(decoration: BoxDecoration(color: Colors.grey),),),
                    ],
                  ) : Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Column(
                        children: [
                          Text(jinridanliagn.toString(),style: TextStyle(fontSize: ScreenUtil().setHeight(25),fontWeight: FontWeight.w600),),
                          Text("今日预约/单")
                        ],
                      ),
                    ],
                  ),
                ),
            ),
            Positioned(
                top: ScreenUtil().setHeight(300),
                child: Container(
                  width: ScreenUtil().setHeight(464),
                  padding: EdgeInsets.only(top: ScreenUtil().setHeight(80),bottom: ScreenUtil().setHeight(30)),
                  color: Colors.white,
                  child: mType=="0" ? Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      GestureDetector(child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Image.asset('assets/images/tuiguang.png',width: ScreenUtil().setWidth(40),height: ScreenUtil().setHeight(40)),
                          Container(
                            padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text("配送费"),
                                Text("免配送费标准",style: TextStyle(fontSize: 13,color: Colors.black26),)
                              ],
                            ),
                          )
                        ],
                      ),onTap: (){
                        MyRoute.push(Peisongfei());
                      },),
                      // SizedBox(width: 1,height: 20,child: DecoratedBox(decoration: BoxDecoration(color: Colors.grey),),),
                    ],
                  ) : Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                    ],
                  ),
                )
            ),
            Positioned(
              top: ScreenUtil().setHeight(250),
                child:Container(
                  width: mType=="0" ? ScreenUtil().setWidth(420) : ScreenUtil().setWidth(450),
                  padding: EdgeInsets.all(10),
                  // padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                  decoration: BoxDecoration(
                      color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(5)) ,
                    boxShadow: [
                      BoxShadow(
                          color: Colors.black12,
                          offset: Offset(0.0, 3.0), //阴影y轴偏移量
                          blurRadius: 5, //阴影模糊程度
                          spreadRadius: 5 //阴影扩散程度
                      )
                    ]
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      GestureDetector(child:
                      Column(
                        children: [
                          // Icon(Icons.local_atm),
                          Image.asset('assets/images/goodsguanli.png',width: ScreenUtil().setWidth(50),height: ScreenUtil().setHeight(50)),
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
                            child: Text("商品分类"),
                          )
                        ],
                      ),
                          onTap: (){
                            print("点击了商品管理");
                            MyRoute.push(GoodsTypePage());
                          }
                      ),

                      mType=="0" ? GestureDetector(child:
                      Column(
                        children: [
                          // Icon(Icons.query_builder),
                          Image.asset('assets/images/user.png',width: ScreenUtil().setWidth(50),height: ScreenUtil().setHeight(50)),
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
                            child: Text("顾客管理"),
                          )
                        ],
                      ),
                          onTap: (){
                            MyRoute.push(GukeList());
                          }
                      ) :
                      GestureDetector(child:
                      Column(
                        children: [
                          // Icon(Icons.query_builder),
                          Image.asset('assets/images/user.png',width: ScreenUtil().setWidth(50),height: ScreenUtil().setHeight(50)),
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
                            child: Text("技师管理"),
                          )
                        ],
                      ),
                          onTap: (){
                            MyRoute.push(JiShiListPage());
                          }
                      ),
                      GestureDetector(child:  Column(
                        children: [
                          // Icon(Icons.directions_car),
                          Image.asset('assets/images/caiwuduizhang.png',width: ScreenUtil().setWidth(50),height: ScreenUtil().setHeight(50)),
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
                            child: Text("财务对账"),
                          )
                        ],
                      ),
                          onTap: (){
                            print("点击了财务对账");
                          }
                      ),
                      GestureDetector(child:  Column(
                        children: [
                          // Icon(Icons.sync),
                          Image.asset('assets/images/jingyininfo.png',width: ScreenUtil().setWidth(50),height: ScreenUtil().setHeight(50)),
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
                            child: Text("经营数据"),
                          )
                        ],
                      ),
                          onTap: (){
                            print("点击了经营数据");
                            MyRoute.push(JingyingFenxi( ));
                          }
                      )
                    ],
                  ),
                )
            ),

          ],
        ),
      )
    );
  }

  //自定义商户状态下拉列表
  List<DropdownMenuItem> getListData(){
    List<DropdownMenuItem> items=new List();
    DropdownMenuItem dropdownMenuItem1=new DropdownMenuItem(
      value: '休息中',
      child:Row(
        children: [
          Text('休息中',style: TextStyle(color: Colors.black,fontSize: 15)),
          Container(
            height: 10,
            width: 10,
            margin: EdgeInsets.fromLTRB(6, 0, 0, 0),
            decoration: BoxDecoration(
              color: Colors.red,
              borderRadius:BorderRadius.circular(20),
            ),
          )
        ],
      ),
    );
    items.add(dropdownMenuItem1);
    DropdownMenuItem dropdownMenuItem2=new DropdownMenuItem(
      value: '营业中',
      child:Row(
        children: [
          Text('营业中',style: TextStyle(color: Colors.black,fontSize: 15)),
          Container(
            height: 10,
            width: 10,
            margin: EdgeInsets.fromLTRB(6, 0, 0, 0),
            decoration: BoxDecoration(
              color: Colors.green,
              borderRadius:BorderRadius.circular(20),
            ),
          )
        ],
      ),
    );
    items.add(dropdownMenuItem2);
    return items;
  }

}